import { PromptTemplate, PromptVersion, PromptShareData, PromptStatistics } from '@/types/prompt';

/**
 * 提示词管理服务
 * 负责处理提示词的CRUD操作、分享、统计等功能
 */
class PromptService {
  private baseUrl: string;

  constructor() {
    this.baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8002/api/v1';
  }

  private async request<T>(endpoint: string, options?: RequestInit): Promise<T> {
    // 暂时使用本地数据，因为后端还没有prompts端点
    console.warn('Prompts API not available, using local data');
    
    // 返回模拟数据以避免404错误
    if (endpoint === '' || endpoint === '/') {
      return [] as T;
    }
    
    const url = `${this.baseUrl}/prompts${endpoint}`;
    const token = localStorage.getItem('access_token');
    
    try {
      const response = await fetch(url, {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          ...(token && { Authorization: `Bearer ${token}` }),
          ...options?.headers,
        },
      });

      if (!response.ok) {
        console.warn(`Prompts API not available: ${response.status}`);
        return [] as T;
      }

      return await response.json();
    } catch (error) {
      console.warn('Prompts API request failed, using fallback:', error);
      return [] as T;
    }

  }

  /**
   * 获取提示词列表
   */
  async getPrompts(params?: {
    category?: string;
    isPublic?: boolean;
    userId?: string;
    page?: number;
    pageSize?: number;
  }): Promise<{ data: PromptTemplate[]; total: number }> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.category) queryParams.append('category', params.category);
      if (params?.isPublic !== undefined) queryParams.append('is_public', params.isPublic.toString());
      if (params?.userId) queryParams.append('user_id', params.userId);
      if (params?.page) queryParams.append('page', params.page.toString());
      if (params?.pageSize) queryParams.append('page_size', params.pageSize.toString());
      
      const query = queryParams.toString();
      return await this.request<{ data: PromptTemplate[]; total: number }>(`${query ? `?${query}` : ''}`);
    } catch (error) {
      console.warn('Failed to fetch prompts from API, using default prompts');
      // 返回默认提示词数据
      return {
        data: [
          {
            id: '1',
            name: '文章写作助手',
            description: '帮助你撰写高质量的文章',
            category: 'writing',
            systemPrompt: '你是一个专业的写作助手，帮助用户创作高质量的文章内容。',
            variables: [],
            tags: ['写作', '文章'],
            version: 1,
            createdAt: new Date(),
            updatedAt: new Date(),
            isPublic: true,
            userId: 'system'
          },
          {
            id: '2',
            name: '创意故事生成器',
            description: '生成有趣的创意故事',
            category: 'creative',
            systemPrompt: '你是一个富有想象力的故事创作者，能够生成引人入胜的故事。',
            variables: [],
            tags: ['创意', '故事'],
            version: 1,
            createdAt: new Date(),
            updatedAt: new Date(),
            isPublic: true,
            userId: 'system'
          },
          {
            id: '3',
            name: '技术文档编写',
            description: '撰写清晰的技术文档',
            category: 'technical',
            systemPrompt: '你是一个技术文档专家，能够编写清晰、准确的技术文档。',
            variables: [],
            tags: ['技术', '文档'],
            version: 1,
            createdAt: new Date(),
            updatedAt: new Date(),
            isPublic: true,
            userId: 'system'
          }
        ],
        total: 3
      };
    }
  }

  /**
   * 获取单个提示词
   */
  async getPromptById(id: string): Promise<PromptTemplate> {
    return this.request<PromptTemplate>(`/${id}`);
  }

  /**
   * 创建提示词
   */
  async createPrompt(prompt: Partial<PromptTemplate>): Promise<PromptTemplate> {
    return this.request<PromptTemplate>('', {
      method: 'POST',
      body: JSON.stringify(prompt),
    });
  }

  /**
   * 更新提示词
   */
  async updatePrompt(id: string, updates: Partial<PromptTemplate>): Promise<PromptTemplate> {
    return this.request<PromptTemplate>(`/${id}`, {
      method: 'PUT',
      body: JSON.stringify(updates),
    });
  }

  /**
   * 删除提示词
   */
  async deletePrompt(id: string): Promise<void> {
    return this.request<void>(`/${id}`, {
      method: 'DELETE',
    });
  }

  /**
   * 获取版本历史
   */
  async getVersionHistory(promptId: string): Promise<PromptVersion[]> {
    return this.request<PromptVersion[]>(`/${promptId}/versions`);
  }

  /**
   * 保存版本
   */
  async saveVersion(promptId: string, content: string, changelog?: string): Promise<PromptVersion> {
    return this.request<PromptVersion>(`/${promptId}/versions`, {
      method: 'POST',
      body: JSON.stringify({ content, changelog }),
    });
  }

  /**
   * 社区分享相关接口
   */
  
  /**
   * 分享提示词到社区
   */
  async sharePrompt(promptId: string, shareData: PromptShareData): Promise<{
    shareId: string;
    shareUrl: string;
    shareCode: string;
  }> {
    // 预留的社区分享接口
    console.log('Sharing prompt:', promptId, shareData);
    
    const shareId = `share_${Date.now()}`;
    const shareCode = Math.random().toString(36).substring(2, 8).toUpperCase();
    
    return Promise.resolve({
      shareId,
      shareUrl: `https://community.example.com/prompts/${shareId}`,
      shareCode
    });
  }

  /**
   * 从分享链接导入提示词
   */
  async importFromShare(shareCode: string): Promise<PromptTemplate> {
    // 预留的导入接口
    console.log('Importing from share code:', shareCode);
    
    // 模拟返回导入的提示词
    return Promise.resolve({
      id: Date.now().toString(),
      name: '导入的提示词',
      description: '从社区导入的提示词模板',
      category: 'custom',
      systemPrompt: '这是一个导入的提示词模板',
      variables: [],
      tags: ['imported', 'community'],
      version: 1,
      createdAt: new Date(),
      updatedAt: new Date(),
      isPublic: false,
      usageCount: 0
    });
  }

  /**
   * 获取社区热门提示词
   */
  async getCommunityPrompts(params?: {
    sort?: 'popular' | 'newest' | 'trending';
    category?: string;
    page?: number;
    pageSize?: number;
  }): Promise<{
    data: PromptTemplate[];
    total: number;
  }> {
    // 预留的社区提示词列表接口
    console.log('Fetching community prompts:', params);
    
    return Promise.resolve({
      data: [],
      total: 0
    });
  }

  /**
   * 点赞/收藏社区提示词
   */
  async likePrompt(promptId: string): Promise<void> {
    // 预留的点赞接口
    console.log('Liking prompt:', promptId);
    return Promise.resolve();
  }

  /**
   * 举报不当内容
   */
  async reportPrompt(promptId: string, reason: string): Promise<void> {
    // 预留的举报接口
    console.log('Reporting prompt:', promptId, reason);
    return Promise.resolve();
  }

  /**
   * 获取分享统计
   */
  async getShareStatistics(shareId: string): Promise<{
    views: number;
    imports: number;
    likes: number;
    comments: number;
  }> {
    // 预留的分享统计接口
    return Promise.resolve({
      views: Math.floor(Math.random() * 1000),
      imports: Math.floor(Math.random() * 100),
      likes: Math.floor(Math.random() * 500),
      comments: Math.floor(Math.random() * 50)
    });
  }

  /**
   * 导出提示词配置
   */
  async exportPrompt(promptId: string): Promise<string> {
    const prompt = await this.getPromptById(promptId);
    return JSON.stringify(prompt, null, 2);
  }

  /**
   * 导入提示词配置
   */
  async importPrompt(jsonConfig: string): Promise<PromptTemplate> {
    try {
      const prompt = JSON.parse(jsonConfig);
      return this.createPrompt(prompt);
    } catch (error) {
      throw new Error('无效的配置文件');
    }
  }

  /**
   * 批量导出
   */
  async exportMultiple(promptIds: string[]): Promise<string> {
    const prompts = await Promise.all(promptIds.map(id => this.getPromptById(id)));
    return JSON.stringify(prompts, null, 2);
  }

  /**
   * 批量导入
   */
  async importMultiple(jsonConfig: string): Promise<PromptTemplate[]> {
    try {
      const prompts = JSON.parse(jsonConfig);
      if (!Array.isArray(prompts)) {
        throw new Error('配置必须是数组格式');
      }
      return Promise.all(prompts.map(p => this.createPrompt(p)));
    } catch (error) {
      throw new Error('无效的配置文件');
    }
  }

  /**
   * 使用统计相关接口
   */

  /**
   * 记录提示词使用
   */
  async recordUsage(promptId: string, metadata?: {
    duration?: number;
    tokenCount?: number;
    score?: number;
  }): Promise<void> {
    return this.request<void>(`/${promptId}/usage`, {
      method: 'POST',
      body: JSON.stringify(metadata || {}),
    });
  }

  /**
   * 获取使用统计
   */
  async getStatistics(promptId: string): Promise<PromptStatistics> {
    return this.request<PromptStatistics>(`/${promptId}/statistics`);
  }

  /**
   * 获取热门提示词排行
   */
  async getTopPrompts(period: 'day' | 'week' | 'month' = 'week'): Promise<{
    prompt: PromptTemplate;
    usage: number;
    trend: 'up' | 'down' | 'stable';
  }[]> {
    return this.request<{
      prompt: PromptTemplate;
      usage: number;
      trend: 'up' | 'down' | 'stable';
    }[]>(`/top?period=${period}`);
  }

  /**
   * 获取用户偏好分析
   */
  async getUserPreferences(userId: string): Promise<{
    favoriteCategories: string[];
    averageVariableCount: number;
    preferredLength: 'short' | 'medium' | 'long';
    mostUsedPrompts: string[];
  }> {
    return Promise.resolve({
      favoriteCategories: ['role', 'style'],
      averageVariableCount: 3,
      preferredLength: 'medium',
      mostUsedPrompts: []
    });
  }

  /**
   * 清理缓存
   */
  clearCache(): void {
    // 清理本地缓存
    console.log('Cache cleared');
  }
}

// 导出单例实例
export const promptService = new PromptService();

// 导出类用于测试
export { PromptService };